package qq

import (
	"api-go/cache"
	"api-go/serializer"
	kuwo "api-go/service/v1/kuwo"
	migu "api-go/service/v1/migu"
	wyy "api-go/service/v1/wyy"
	"api-go/util"
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/go-redis/redis/v8"
)

// 歌曲所需信息
type Song struct {
	Ids  string `form:"id"`
	Br   string `form:"br"`
	Type string `form:"type"` //vip播放源，1酷我 2咪咕 3网易云
}

//获取歌曲链接
func (service *Song) SongUrl() *serializer.Response {

	if val := service.Ids; val != "" {
		service.Ids = val
	} else {
		service.Ids = "002mZevo3wHvsc"
	}

	if val := service.Br; val != "" {
		service.Br = val
	} else {
		service.Br = "1"
	}

	var s, e string
	if service.Br == "1" {
		s = "M500"
		e = ".mp3"
	} else if service.Br == "2" {
		s = "M800"
		e = ".mp3"
	} else {
		s = "F000"
		e = ".flac"
	}

	if val := service.Type; val != "" {
		service.Type = val
	} else {
		service.Type = "1"
	}

	filename := s + service.Ids + service.Ids + e

	url := "https://u.y.qq.com/cgi-bin/musicu.fcg?format=json&data={\"req\":{\"module\":\"CDN.SrfCdnDispatchServer\",\"method\":\"GetCdnDispatch\",\"param\":{\"guid\":\"658650575\",\"calltype\":0,\"userip\":\"\"}},\"req_0\":{\"module\":\"vkey.GetVkeyServer\",\"method\":\"CgiGetVkey\",\"param\":{\"filename\":[\"" + filename + "\"],\"guid\":\"658650575\",\"songmid\":[\"" + service.Ids + "\"],\"songtype\":[0],\"uin\":\"0\",\"loginflag\":1,\"platform\":\"20\"}},\"comm\":{\"uin\":0,\"format\":\"json\",\"ct\":24,\"cv\":0}}"
	fmt.Println(url)
	res, err := util.QQGet(url)
	if err != nil {
		return err
	}
	//从map[string]interface{}中取值
	newRes := res.(map[string]interface{})["req_0"].(map[string]interface{})["data"].(map[string]interface{})["midurlinfo"].([]interface{})
	var ress interface{}
	for _, r := range newRes {
		ress = r.(map[string]interface{})["purl"]
	}

	//获取歌曲的详细信息
	out := map[string]interface{}{}

	url = "https://c.y.qq.com/v8/fcg-bin/fcg_play_single_song.fcg?format=json&songmid=" + service.Ids

	resss, errs := util.QQGet(url)
	if errs != nil {
		return serializer.ErrorResponse(serializer.CodeUnknownError)
	}
	if len(resss.(map[string]interface{})["data"].([]interface{})) == 0 {
		return serializer.ErrorResponse(serializer.CodeUnknownError)
	}
	ressss := resss.(map[string]interface{})["data"].([]interface{})[0].(map[string]interface{})
	out["id"] = ressss["mid"]
	out["album"] = ressss["album"].(map[string]interface{})["name"]
	out["name"] = ressss["name"].(string)
	out["singer"] = ressss["singer"].([]interface{})[0].(map[string]interface{})["name"].(string)
	out["picUrl"] = "https://y.qq.com/music/photo_new/T002R300x300M000" + ressss["album"].(map[string]interface{})["mid"].(string) + ".jpg"
	out["platform"] = "qq"
	//vip或者高品质歌曲获取不到的情况下
	if ress.(string) == "" {
		if service.Type == "3" {
			out["url"] = wyy.UsingWyySong(out["name"].(string), out["singer"].(string), service.Br)
		} else if service.Type == "2" {
			out["url"] = migu.UsingMiguSong(out["name"].(string), out["singer"].(string), service.Br)
		} else {
			out["url"] = kuwo.UsingKwSong(out["name"].(string), out["singer"].(string), service.Br)
		}
	} else {
		out["url"] = "https://isure.stream.qqmusic.qq.com/" + ress.(string)
	}

	//获取歌词
	url = "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?format=json&nobase64=1&g_tk=5381&songmid=" + service.Ids
	b, errs := util.QQGet(url)
	if errs != nil {
		return serializer.ErrorResponse(serializer.CodeUnknownError)
	}
	if strconv.FormatFloat(b.(map[string]interface{})["code"].(float64), 'f', -1, 64) == "0" {
		out["lyric"] = b.(map[string]interface{})["lyric"]
	} else {
		out["lyric"] = "failed"
	}
	return serializer.OkResponse(out)
}

//获取歌曲歌词
func (service *Song) SongLyric() *serializer.Response {
	if val := service.Ids; val != "" {
		service.Ids = val
	} else {
		service.Ids = "004O1DHG4MjYOi"
	}

	url := "https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg?format=json&nobase64=1&g_tk=5381&songmid=" + service.Ids

	res, err := util.QQGet(url)
	if err != nil {
		return err
	}
	return serializer.OkResponse(res)
}

//获取最新音乐
func (service *Song) SongNew() *serializer.Response {
	//定义redis key和判断redis是否有该值
	redisKey := "qq-song-new"
	redisResult, err := cache.RedisClient.Get(ctx, redisKey).Result()
	//若redis没有该值则执行获取
	if err == redis.Nil {
		url := "https://u.y.qq.com/cgi-bin/musicu.fcg?data={\"comm\":{\"ct\":24},\"new_song\":{\"module\":\"newsong.NewSongServer\",\"method\":\"get_new_song_info\",\"param\":{\"type\":5}}}"
		res, err := util.QQGet(url)
		if err != nil {
			return err
		}

		newRes := res.(map[string]interface{})["new_song"].(map[string]interface{})["data"].(map[string]interface{})["songlist"].([]interface{})
		out := []map[string]interface{}{}
		for i := 0; i < 6; i++ {
			out = append(out, newRes[i].(map[string]interface{}))
		}
		//将结果转为Json数据
		b, e := json.Marshal(out)
		if e != nil {
			fmt.Println(err)
		}
		//转为string存入redis
		e = cache.RedisClient.Set(ctx, redisKey, string(b), 24*time.Hour).Err()
		if e != nil {
			fmt.Println("err1", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}

		return serializer.OkResponse(out)
	} else if err != nil {
		fmt.Println("err2", err)
		return serializer.ErrorResponse(serializer.RedisError)
	} else {
		//将从redis获取的结果（string类型）转为map[string]inerface{}
		bodyMapData := []map[string]interface{}{}
		err = json.Unmarshal([]byte(redisResult), &bodyMapData)
		if err != nil {
			fmt.Println("err3", err)
			return serializer.ErrorResponse(serializer.RedisError)
		}
		return serializer.OkResponse(bodyMapData)
	}
}
